package com.treasure.web.controller.system;

import com.treasure.common.enums.IdentitiesEnum;
import com.treasure.common.enums.LoginRouteEnum;
import com.treasure.common.enums.RegisterChannelEnum;
import com.treasure.common.exception.ServiceException;
import com.treasure.common.model.PageResult;
import com.treasure.common.model.SessionUser;
import com.treasure.common.reponse.Response;
import com.treasure.common.types.Corp;
import com.treasure.infrastructure.model.po.CorpTrialApprove;
import com.treasure.infrastructure.model.po.CorpUserInfo;
import com.treasure.web.command.request.*;
import com.treasure.web.command.request.chat.CorpChatHistoryDetailRequest;
import com.treasure.web.command.request.login.LoginRequest;
import com.treasure.web.command.response.*;
import com.treasure.web.service.*;
import com.treasure.web.service.impl.CorpManageService;
import lombok.RequiredArgsConstructor;
import org.apache.commons.lang3.BooleanUtils;
import org.springframework.validation.annotation.Validated;
import org.springframework.web.bind.annotation.PostMapping;
import org.springframework.web.bind.annotation.RequestBody;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RestController;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.io.IOException;
import java.util.List;

/**
 * 系统管理后台
 *
 * @author sunhongmin
 * @date 2023/9/10 10:34
 * @description 系统管理后台
 */
@RestController
@RequestMapping("/treasure/sys/admin")
@RequiredArgsConstructor
public class SystemManagerController extends LoginHelper {

    private final CorpManageService corpManageService;
    private final IAccountService accountService;
    private final ICorpAccessTokenService corpAccessTokenService;
    private final ICorpTrialApproveService corpTrialApproveService;
    private final IChatHistoryService chatHistoryService;
    private final IModelUsageDetailsService modelUsageDetailsService;

    /**
     * 超级管理员登录
     *
     * @param loginRequest
     * @param servletResponse
     * @return
     */
    @PostMapping("/login")
    public Response<String> login(@RequestBody @Validated({LoginRequest.AdminLoginValiadate.class}) LoginRequest loginRequest, HttpServletResponse servletResponse) {
        List<CorpUserInfo> corpUserInfoList = accountService.login(loginRequest, LoginRouteEnum.SUPER_ROOT_LOGIN_ROUTE);
        if (corpUserInfoList.size() > 1) {
            throw new ServiceException("该账户同时属于两个及以上企业/高校主体的管理员，请选择主体后进行登录");
        }
        // 身份校验
        CorpUserInfo superAdminUser = corpUserInfoList.stream().findFirst().orElse(new CorpUserInfo());
        if (BooleanUtils.isNotTrue(superAdminUser.getHasSuperAdmin())) {
            throw new ServiceException("该账户不具有系统后台管理权限，请联系管理员");
        }
        String token = getToken(superAdminUser);
        addCookie(servletResponse, token);
        SessionUser sessionUser = getSessionUserCache(superAdminUser, IdentitiesEnum.SUPER_ROOT_ADMIN);
        putCache(token, sessionUser);
        return Response.success("登录成功");
    }

    /**
     * 超级管理员登出
     *
     * @return
     */
    @PostMapping("/logout")
    public Response<?> logout(HttpServletRequest servletRequest) {
        return tokenLogout(servletRequest);
    }

    /**
     * 企业试用申请列表
     *
     * @return
     */
    @PostMapping("corp/trial/approve/list")
    public Response<PageResult<CorpTrialApproveResponse>> corpTrialApproveList(@RequestBody GetTrialApproveRequest getTrialApproveRequest) {
        return Response.success(corpTrialApproveService.corpTrialApproveList(getTrialApproveRequest));
    }

    /**
     * 企业试用申请标记同意
     *
     * @param corpTrialApprovedRequest
     * @return
     */
    @PostMapping("corp/trial/approved")
    public Response<String> corpTrialApproved(@Validated @RequestBody CorpTrialApprovedRequest corpTrialApprovedRequest) {
        corpTrialApproveService.corpTrialApproved(corpTrialApprovedRequest.getIdList());
        return Response.success();
    }

    /**
     * 后台企业/高校账号创建
     *
     * @param createUnofficialCorpAccountRequest
     * @return
     */
    @PostMapping("/create")
    public Response<?> createUnOfficialCorpAccount(@RequestBody @Validated CreateCorpAccountRequest createUnofficialCorpAccountRequest) throws IOException, IllegalAccessException {
        accountService.createCorpAccount(createUnofficialCorpAccountRequest, RegisterChannelEnum.SYSTEM_REGIS);
        return Response.success();
    }

    /**
     * 企业列表
     *
     * @param corpInfoQuery
     * @return
     */
    @PostMapping("/corp/list")
    public Response<PageResult<CorpInfoResponse>> corpList(@RequestBody CorpInfoQuery corpInfoQuery) {
        return Response.success(corpManageService.listCorpInfo(corpInfoQuery));
    }

    /**
     * 获取企业/高校授权信息 accountToken
     *
     * @param getCorpAccountTokenRequest
     * @return
     */
    @PostMapping("/corp/accountToken")
    public Response<CorpAccountTokenResponse> getCorpAccountToken(@RequestBody @Validated GetCorpAccountTokenRequest getCorpAccountTokenRequest) {
        return Response.success(corpAccessTokenService.getCorpAccountTokenInfo(new Corp(getCorpAccountTokenRequest.getCorpId())));
    }

    /**
     * 企业信息编辑（开通、停用、编辑到期时间、编辑试用人数）
     *
     * @param corpEditRequest
     * @return
     */
    @PostMapping("/edit")
    public Response<String> accountEdit(@RequestBody @Validated CorpEditRequest corpEditRequest) {
        accountService.corpEdit(corpEditRequest);
        return Response.success();
    }

    /**
     * 系统对话明细列表
     *
     * @param corpChatHistoryDetailRequest
     * @return
     */
    @PostMapping("/conversation/list")
    public Response<PageResult<ConversationListResponse>> conversationList(@RequestBody CorpChatHistoryDetailRequest corpChatHistoryDetailRequest) {
        PageResult<ConversationListResponse> conversationListResponsePageResult = chatHistoryService.queryChatHistoryDetailList(corpChatHistoryDetailRequest, corpChatHistoryDetailRequest.getCorpId());
        return Response.success(conversationListResponsePageResult);
    }

    /**
     * 模型调用明细列表
     * @param modelUsageDetailRequest
     * @return
     */
    @PostMapping("/model/usage/list")
    public Response<PageResult<ModelUsageDetailsResponse>> modelUsageList(@RequestBody ModelUsageDetailRequest modelUsageDetailRequest) {
        return Response.success(modelUsageDetailsService.modelUsageList(modelUsageDetailRequest));
    }

    // 新建企业管理员

    // 模拟登录


}
